package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"strconv"
	"work/websocket/server_formal/hub"
)

func wsServer() gin.HandlerFunc {
	return func(c *gin.Context) {
		fmt.Println("/ws")
		userName := c.Query("username")
		fmt.Println("userName= ", userName)
		group := c.Query("group")
		if group == "" {
			c.JSON(201, gin.H{
				"status": false,
				"data":   "No Group Setting",
			})
			return
		}
		//Upgrader用于在升级时让websocket包获取请求的信息，并在执行Upgrade方法验证这个websocket连接是否合法
		upgrader := websocket.Upgrader{
			Subprotocols: []string{c.GetHeader("Sec-WebSocket-Protocol")},
			CheckOrigin: func(r *http.Request) bool {
				origin := r.Header.Get("Origin")
				if origin == "" {
					return false
				}
				return true
			}}

		conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
		if err != nil {
			log.Println("连接建立失败")
			return
		}
		//返回了错误
		g, err := strconv.Atoi(group)
		if err != nil {
			c.JSON(200, gin.H{
				"status": false,
				"data":   "访问格式不正确",
			})
			return
		}
		connection := hub.Center.AddIntoGroup(userName, g, conn)
		fmt.Println("得到一个新连接")
		go connection.Receive()
		go connection.Send()
	}
}
